package com.itheima.reggie.web;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.service.ICategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/category")
public class CategoryController {

    @Autowired
    ICategoryService categoryService;

    /**
     * 新增分类
     */
    @PostMapping
    public R<String> save(@RequestBody Category category) {
        categoryService.save(category);
        return R.success("添加成功");
    }

    /**
     * 分页查询
     */
    @GetMapping("/page")
    public R<Page> page(Integer page, Integer pageSize) {
        //分页构造器
        Page<Category> pageInfo = new Page<>(page, pageSize);
        //条件构造器
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        //添加排序条件
        queryWrapper.orderByAsc(Category::getSort);
        //分页查询
        categoryService.page(pageInfo, queryWrapper);

        return R.success(pageInfo);
    }

    /**
     * 删除分类
     */

    @DeleteMapping
    public R<String> remove(Long id) {
        //调用业务层自定义的删除方法
        boolean result = categoryService.rmeById(id);

        return result ? R.success(null) : R.error("无法删除分类，当前分类下存在菜品或套餐");
    }

    /**
     * 更新
     */
    @PutMapping
    public R update(@RequestBody Category category) {
        categoryService.updateById(category);
        return R.success("修改成功");
    }

/**
 * 根据条件查询分类数据
 * */
    @GetMapping("/list")
    public  R<List<Category>> dishCategory(Category category){
       //条件构造器
        LambdaQueryWrapper<Category> categoryqueryWrapper = new LambdaQueryWrapper<>();
       //添加条件
        categoryqueryWrapper.eq(category.getType() !=null,Category::getType,category.getType());
       //添加排序条件
        categoryqueryWrapper.orderByAsc(Category::getSort).orderByDesc(Category::getUpdateTime);
        //执行
        List<Category> list = categoryService.list(categoryqueryWrapper);

        return R.success(list);
    }

}
